<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\ExportReport\ExportReportJiNanLuYuanController;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Exception;


class RequestGwDataController extends Controller
{
    private $url='http://22.40.212.237:8899/rmcp-gqj-web/api/';//接口对接地址
    private $orgId='3d3f9af3001b4507869eab082f3e10f1';//试验中心组织机构id

    /**
     * 获取存量待检工器具列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public  function getStock(Request $request){
        $contract_id = $request->id;
        $res = $this->getData($contract_id);
        if ($res){
            return response()->json(['code'=>1,'msg'=>'导入成功']);
        }else{
            return response()->json(['code'=>0,'msg'=>'导入失败']);
        }
    }

    public function codeGetGqj(Request $request){
        $contract_id = $request->id;//获取批次的id
        $qrcode_data = $request->qrcode_input;//获取扫码数据
        $list = array_unique($qrcode_data);//获取去重以后的扫码数据
        $url = "syzx/getGqjBookOrStockInfoByScan";
        $param['iCodeList']= $list;
        //        $res = $this->post_url($url,json_encode($param));
        $res = file_get_contents(__DIR__."\\gw_new.json");//测试用返回的接口数据
        $res_data = json_decode($res,true);
        if ($res_data['successful']){
            $data = $res_data['resultValue'];
            $res = $this->insert_data($data,$contract_id);
            if ($res){
                return response()->json(['code'=>1,'msg'=>'导入成功']);
            }else{
                return response()->json(['code'=>0,'msg'=>'导入失败']);
            }
        }else{
            return response()->json(['code'=>0,'msg'=>'导入失败']);
        }
    }

    /**
     * 将实验数据上传到风控平台 安全工器具试验结果保存接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function upData(Request $request){
        $url = "syzx/saveGqjTestInfo";
        $id  = $request->input('id');//获取要上传的实验数据的ID
        $data =  DB::table('a_sample_info as B')
                ->leftJoin('a_contract_gaiyao as A', 'A.id', '=', 'B.contract_gaiyao_id')
                ->leftJoin('a_contract as C', 'A.contract_id', '=', 'C.id')
                ->where('B.id', $id)
                ->select(['B.third_book_id','B.third_pk_id','B.contract_id','B.contract_gaiyao_id','B.tester_names','A.third_status','A.tool_id','A.std_id',"B.test_time",'B.next_time','C.batchNum','B.bar_code'])
                ->first();//查询上传数据的关联信息。合同Id工器具id 实验项目id
        if ($data){
            $ExportReportCon = new \App\Http\Controllers\Admin\ExportReportController();
            //获取实验机构名称
            $client_name = DB::table('a_contract')->where('id',$data->contract_id)->value('client_name');
            // '/{{config('constant.name_admin')}}/exportReport/export?sample=1&id=' + id
            $request->offsetSet('sample',1); //单样品检测报告
            $request->offsetSet('storeFile','reports/'.$data->batchNum.'/'.$data->bar_code.'.xls'); //生成报告的文件卢荣景
            try{
                $filePath = $ExportReportCon->export($request);//生成单独的报告文件
            }catch(\Exception $e){
                return '报告生成失败，请检查！';
            }
            //组建上传数据
            $param= [
                'pkGqjcheckId'=>$data->third_pk_id,
                'bookid'=>$data->third_book_id,
                'sendmechanismid'=>$this->orgId,
                'status'=>$data->third_status,
                'sendmechanism'=>$client_name,
                'fileName'=>basename($filePath),
                'fileContent'=>file_get_contents($filePath),
            ];

            $test_item_data = DB::table('a_item_data as a')
                ->leftJoin('a_contract_gaiyao as g','g.contract_gaiyao_id','=','c.id')
                ->leftJoin('manager as m','a.manager_id','=','m.id')
                ->leftJoin('a_testitem as b','a.item_id','=','b.id')
                ->leftJoin('a_std_tool_item_rel as r',function ($query)
                {
                    $query->on('r.std_id','=','g.std_id')->on('r.tool_id','=','g.tool_id')->on('r.testitem_id','=','a.item_id');
                })
                ->where('a.sample_info_id',$id)
                ->select(['a.res','m.realname','a.utime','a.item_id','b.name as tool_name','r.third_item_code'])
                ->wherein('a.res',[0,1])->get();
            if ($test_item_data){
                $test_arr =[];
                $cycle = DB::table('a_std_tool_rel')->where('std_id',2)->where('tool_id',$data->tool_id)->value('cycle');
                foreach ($test_item_data as $k=>$v){
                    /*试验数据内容、文件内容*/
                    $gqjCheckResultList = [
                        'pkTestInfoId'=>'', //试验主键id,风控平台生成，传空即可
                        'pkGqjCheckId'=>$data->third_pk_id,
                    ];
                    $testResult = intval(!$v->res);//风控平台跟我们的结果相反。直接取反
                    //获取第三方实验项目的主键Id
                    $arr = [
                        'testDate'=>$v->utime,
                        'testUser'=>$v->realname,
                        'testResult'=>$testResult,
                        'lastTestTime'=>$data->test_time,
                        'nextTestTime'=>$data->next_time,
                        'testPeriod'=>$cycle.'年',
                        'testProject'=>$v->tool_name,
                        'pkDictDetailid'=>$v->third_item_code,
                        'gqjCheckResultList'=>$gqjCheckResultList,
                    ];
                    $test_arr[]=$arr;
                }
                $param['testList']=$test_arr;
                $up_res = $this->post_url($url,json_encode($param));
                $up_res = json_decode($up_res,true);
                $up_res['successful']=true;
                if ($up_res['successful']){
                    @unlink($filePath);
                    return response()->json(['code'=>1,'msg'=>'上传成功']);
                }else{
                    return response()->json(['code'=>0,'msg'=>'上传失败']);
                }
            }else{
                return response()->json(['code'=>0,'msg'=>'暂无实验结果']);
            }

        }else{
            return response()->json(['code'=>0,'msg'=>'暂无需要上传的数据']);
        }
    }


    /**
     * 获取新购置待检工具
     * @param $contract_id
     * @return bool
     */
    protected function getData($contract_id){
        $url = $this->url.'syzx/getGqjTestInfo';//新购置待检器具地址
        $param = json_encode(['orgId'=>$this->orgId]);//试验中心组织机构id
//        $res =  $this->post_url($url,$param);//返回的数据
        $res = file_get_contents(__DIR__."\\gw_new.json");//测试用返回的接口数据
        $res_data = json_decode($res,true);
        if ($res_data['successful']){
            $data = $res_data['resultValue'];
            $res = $this->insert_data($data,$contract_id);
            return $res;
        }else{
            return false;
        }
    }

    /**
     * 插入第三方数据到数据库
     * @param $data
     * @param $contract_id
     * @return bool
     */
    protected function insert_data($data,$contract_id){
        $db_res=false;
        $std_id = 2;//目前写死为DL/T 1476-2015标准
        $std_num = DB::table('a_standard')->where('id',$std_id)->value('num');
        //查询批次的编号
        $contract = DB::table('a_contract')->where('id', $contract_id)->select('batchNum','client_name')->first();
        $batch_num = $contract->batchNum;
        $client_name = $contract->client_name;

        DB::beginTransaction();//开启事务因为是批量操作如果有一个不成功整个回滚
        try {
            foreach ($data as $k=>$v){
                $old_data = DB::table('a_sample_info')->where('contract_id',$contract_id)->where('third_book_id',$v['bookid'])->first();//查询这个工器具这个批次是否已经录入过
                if ($old_data){
                    continue;
                }
                $tool_info = DB::table('a_tool')->where('third_id',$v['classifyid'])->get()->first();//根据返回的工器具三方ID获取系统的工器具ID
                if ($tool_info){
                    $tool_id = $tool_info->id;
                    $unit=$tool_info->unit;
                    $new_arr = [
                        'contract_id'=>$contract_id,//批次ID
                        'std_num'=>$std_num,//标准号
                        'std_id'=>$std_id,//系统的标准Id
                    ];
                    //返回的检测项目
                    $item_names=[];
                    $item_ids=[];
                    foreach ($v['syxmInfo'] as $kk=>$vv){
                        $item_info = DB::table('a_std_tool_item_rel as a')->leftJoin('a_testitem as t','a.testitem_id','=','t.id')->where('a.std_id',$std_id)->where('a.tool_id',$tool_info->id)->where('a.third_item_code',$vv['pkDictDetailId'])->get(['t.id','t.name'])->first();
                        if ($item_info){
                            $item_names[]=$vv['value'];
                            $item_ids[] = $item_info->id;
                        }
                    }
                    $new_arr['item_names']=implode(',',$item_names);
                    $new_arr['item_ids']=implode(',',$item_ids);
                    //额定电压
                    $new_arr['voltage']='/';
                    $new_arr['vol_id']=0;//额定电压系统id
                    $new_arr['class']='/';//系统的分类名
                    $new_arr['tool_name']=$tool_info->name;//系统的工具名
                    $new_arr['tool_id']=$tool_id;//系统的工具id
                    $new_arr['count']=1;//检测数量 返回数据无默认1
                    $new_arr['unit']=$unit;//系统查询出的工具单位
                    $new_arr['remark']='';
                    $new_arr['sub_count']=1;
                    $new_arr['third_status']=$v['status'];
                    /* 制作条码开始索引----------------------- end */
                    $res1 = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->orderBy('index','desc')->first();
                    //1.在gaiyao表中记录不为空
                    if($res1) {
                        $index = $res1->index + $res1->count;
                    }
                    else {
                        //2.在gaiyao表中记录为空
                        $index = 1;
                    };

                    $count =  1;//检测的样品数量。每次数据一条默认为1
                    //格式化字符串
                    $chars_count = DB::table('setting')->where('id', '1')->value('chars_count');
                    $format_string = "%0{$chars_count}d";
                    /* 制作条码范围-------------------------start */
                    //开始的条码
                    $str_start = $batch_num.sprintf($format_string, $index);
                    //结尾的条码
                    $str_end = $batch_num.sprintf($format_string, $index + $count-1);
                    $new_arr['bar_codes'] = $str_start.'～'.$str_end;
                    $new_arr['index']=$index;
                    //插入数据    insert 返回true 或 false
                    $contract_gaiyao_id = DB::table('a_contract_gaiyao')->insertGetId($new_arr);
                    // foreach ($data_gaiyao as $val) {

                    $sub_count = $new_arr['sub_count']; //一套样品包含的数量，例如一套绝缘杆包含3节
                    // $srt_item = $val->item_ids;

                    $arr_item = $item_ids;
                    for($i = 0; $i < $count; $i ++) {
                        $str_suf = sprintf($format_string, $index ++); //样品号的后几位
                        for($j = 1; $j <= $sub_count; $j ++) {
                            if($sub_count > 1) {
                                # 如果一套样品包含多件，则加后缀
                                $barcode_suf = "-$j";
                            }
                            else {
                                # code...
                                $barcode_suf = "";
                            }
                            $bar_code = $batch_num.$str_suf.$barcode_suf;
                            //构建要插入的数据
                            $data_sample_insert = [
                                'bar_code'           => $bar_code,
                                'bar_code_1st'       => $bar_code,   //新增的和bar_code一样
                                'remark'             => "",
                                'contract_id'        => $contract_id,
                                'contract_gaiyao_id' => $contract_gaiyao_id,
                                'key'                => str_random(6), //用六位随机字符串作为密码
                                'third_pk_id'           => $v['pkGqjCheckId'],//第三方的送检id
                                'third_book_id'           => $v['bookid'],//第三方的台账id
                                'manufacturer'           => $v['facName'],//第三方的生产厂家
                                'production_date'           => $v['factoryTime'],//第三方的生产日期
                                'guige_xinghao'           => $v['gqjStandard'],//第三方工器具的规格型号
                                'ctime'           => date('Y-m-d H:i:s',time()),
                                'gqj_ID'           => $v['icode'],//第三方的工器具编码唯一
                                'self_num'           => $v['icode'],//自编号
                                'place'           => $client_name,//检测地点
                            ];
                            //插入数据    insertGetId 返回 ID 值
                            $sampleInfoId = DB::table('a_sample_info')->insertGetId($data_sample_insert);
                            $testdataKeyIds = DB::table('a_testdata_key')->where(['std_id'=>$std_id,'tool_id'=>$tool_id])->whereIn('item_id',$item_ids)->pluck('id');
                            $data_item = $data_input = [];
                            foreach($arr_item as $vv) {
                                //构建要插入的数据
                                $data_item[] = [
                                    'contract_id'        => $contract_id,
                                    'contract_gaiyao_id' => $contract_gaiyao_id,
                                    'sample_info_id'     => $sampleInfoId,
                                    'item_id'            => $vv,
                                    'station_ids'        => DB::table('a_std_tool_item_rel')->where(['tool_id' => $tool_id, 'testitem_id' => $vv])->value('station_ids'),
                                ];
                            }
                            //a_item_data插入数据    insert 返回true 或 false
                            $result = DB::table('a_item_data')->insert($data_item);
                            if ($testdataKeyIds){
                                //构建a_input_data要插入的数据
                                foreach($testdataKeyIds as $testdataKeyId){
                                    $data_input[] = [
                                        'sample_info_id' => $sampleInfoId,
                                        'testdata_key_id' => $testdataKeyId,
                                    ];
                                }
                            }
                            //a_input_data插入数据
                            if ($data_input){
                                DB::table('a_input_data')->insert($data_input);
                            }

                        }
                    }
                    $db_res=true;
                    DB::commit();
                }
            }
        }catch (QueryException $exception){
            DB::rollBack();
        }
        return $db_res;
    }

    /**
     * 同步第三方工器具信息
     * @return void
     */
    public function getTool(){
        $url = $this->url.'gqjsyxm/selectSyxmList';//获取检测工器具和检测项目信息的接口地址
        $param = json_encode(['orgId'=>$this->orgId]);//试验中心组织机构id
//        $res =  $this->post_url($url,$param);//返回的数据
        $res = file_get_contents(__DIR__."\\tool_data.json");//测试用返回的接口数据
        $res_data = json_decode($res,true);
        if ($res_data['successful']){
            $data = $res_data['resultValue'];
            $up_res = false;
            DB::beginTransaction();
            try {
                foreach ($data as $k=>$v){
//                    匹配系统工器具名字
                    switch ($v['gqjClass']){
                        case "导轨自锁器":
                            $name = '自锁器';
                            break;
                        case "个人保安接地线":
                            $name = '个人保安线';
                            break;
                        case "绝缘操作杆":
                            $name = '绝缘杆';
                            break;
                        case "验电器":
                            $name = '电容型验电器';
                            break;
                        case "绝缘遮蔽罩":
                            $name = '绝缘罩';
                            break;
                        case "脚扣":
                            $name = '登杆脚扣';
                            break;
                        case "绝缘脚手架":
                            $name = '快装脚手架';
                            break;
                        case "绝缘鞋":
                            $name = '辅助型绝缘鞋';
                            break;
                        default:
                            $name = $v['gqjClass'];
                            break;
                    }
                    $tool_data = DB::table('a_tool')->where('name',$name)->first();//查询系统中工器具对应的信息
                    if ($tool_data){
                        //如果存在对比是否更新过第三方ID如果没有就更新第三方的工器具ID信息
                        if ($tool_data->third_id!=$v['gqjClassId']){
                            DB::table('a_tool')->where('id',$tool_data->id)->update(['third_id'=>$v['gqjClassId']]);
                        }
                        $res_item_data = $v['data'];//第三方工器具需要检测的项目
                        //获取系统这个工器具需要检测的项目
                        $item_ids = DB::table('a_std_tool_item_rel')->where('std_id',2)->where('tool_id',$tool_data->id)->pluck('testitem_id')->toArray();
                        foreach ($res_item_data as $keys=>$vals){
//                            循环更新系统检测项目和第三方检测项目关联信息
                            foreach ($vals['testList'] as $kk=>$vv){
                                header('Content-type:text/html;charset=utf-8');
                                $search_str = '试验';
                                if (mb_stripos($vv['value'],$search_str)){
                                    $vv['value']=str_replace($search_str,'',$vv['value']);
                                }
                                if ($vv['value']=='启动电压'){
                                    $vv['value']='起动电压';
                                }
//                                查询系统的检测项目如果存在就关联
                                $item_data = DB::table('a_testitem')->whereIn('id',$item_ids)->where('name',$vv['value'])->first();
                                if ($item_data){
//                                    $item_data_third_id = explode(',',$item_data->third_id);//获取已经关联的第三方项目信息
////                                    判断是否已关联如果没有就添加一个信息，更新系统的检测项目关联信息
//                                    if (!in_array($vv['pkDictDetailid'],$item_data_third_id)){
//                                        array_push($item_data_third_id,$vv['pkDictDetailid']);
//                                    }
//                                    $third_ids = implode(',',$item_data_third_id);
                                    DB::table('a_std_tool_item_rel')->where('testitem_id',$item_data->id)->where('tool_id',$tool_data->id)->where('std_id',2)->update(['third_item_code'=>$vv['pkDictDetailid']]);
                                }
                            }
                        }
                    }
                }
                $up_res=true;
                DB::commit();
            }catch (Exception $e){
                Log::error($e->getMessage());
                DB::rollBack();
            }
            if ($up_res){
                return response()->json(['code'=>1,'msg'=>'同步信息请求成功']);
            }else{
                return response()->json(['code'=>0,'msg'=>'系統更新錯誤']);
            }

        }else{
            return response()->json(['code'=>0,'msg'=>'同步信息请求失败']);
        }
    }


//    protected function post_url($url,$data){
//        $post_data = http_build_query($data);
//        $options=[
//            'http'=>[
//                'method'=>'post',
//                'header'=>'Content-Type:application/x-www-form-urlencoded',
//                'content'=>$post_data,
//                'timeout'=>5*60,
//            ]
//        ];
//        $context= stream_context_create($options);
//        $result = file_get_contents($url,false,$context);
//        dd($result);
//    }

    protected function post_url($url,$data){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,false);
        curl_setopt($ch,CURLOPT_HTTPHEADER,[
            'Content-Type:application/json;charset=UTF-8'
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

}
